<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item>
            <el-input v-model="query.params.url" placeholder="URL" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.operationType" placeholder="操作类型" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.parentId" placeholder="上级权限编号" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.type" placeholder="类型" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.platformType" clearable placeholder="客户端类型" style="width:100%">
              <el-option v-for="item in query.platformTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'AUTHORITY_LIST'" type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'AUTHORITY_EDIT'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row row-key="id">
        <el-table-column label="名称" width="210">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="URL" width="168">
          <template slot-scope="scope">
            {{ scope.row.url }}
          </template>
        </el-table-column>
        <el-table-column label="路径" width="168">
          <template slot-scope="scope">
            {{ scope.row.path }}
          </template>
        </el-table-column>
        <el-table-column label="图标" width="110">
          <template slot-scope="scope">
            {{ scope.row.icon }}
          </template>
        </el-table-column>
        <el-table-column label="识别代码" width="110">
          <template slot-scope="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="110" prop="type" :formatter="typeFormat">
        </el-table-column>
        <el-table-column label="操作类型" width="110" prop="operationType" :formatter="operationTypeFormat">
        </el-table-column>
        <el-table-column label="上级权限编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.parentId }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作" width="300">
          <template slot-scope="scope">
            <el-link v-has="'AUTHORITY_EDIT'" type="warning" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">修改</el-link>
            <el-divider v-has="'AUTHORITY_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'AUTHORITY_REMOVE'" type="danger" class="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link v-has="'AUTHORITY_SUB_EDIT'" type="success" class="el-icon-folder-add" @click="handleSubEditDelete(scope.$index, scope.row)">添加子功能</el-link>
            <el-divider v-has="'AUTHORITY_SUB_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'AUTHORITY_BELONG_2_ROLE_AND_OTHERS'" type="primary" class="el-icon-delete" @click="handleAssignOrgan(scope.$index, scope.row)">组织赋权</el-link>
            <el-divider v-has="'AUTHORITY_BELONG_2_ROLE_AND_OTHERS'" direction="vertical"></el-divider>
            <el-link v-has="'AUTHORITY_BELONG_2_ROLE_AND_OTHERS'" type="primary" class="el-icon-delete" @click="handleAssignRole(scope.$index, scope.row)">角色赋权</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 80, 120, 200, 500, 1000]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="权限编号">
            <el-input v-model="form.id" auto-complete="off" :disabled="true" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="form.name" auto-complete="off" />
          </el-form-item>
          <el-form-item label="URL">
            <el-input v-model="form.url" auto-complete="off" />
          </el-form-item>
          <el-form-item label="路径">
            <el-input v-model="form.path" auto-complete="off" />
          </el-form-item>
          <el-form-item label="图标">
            <el-input v-model="form.icon" auto-complete="off" />
          </el-form-item>
          <el-form-item label="识别代码">
            <el-input v-model="form.code" auto-complete="off" />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="form.operationType" placeholder="操作类型" auto-complete="off" style="width:100%">
              <el-option v-for="item in query.operationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户端类型">
            <el-select v-model="form.platformType" placeholder="客户端类型" auto-complete="off" style="width:100%">
              <el-option v-for="item in query.platformTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="上级权限编号">
            <el-input v-model="form.parentId" auto-complete="off" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="form.type" placeholder="类型" style="width:100%">
              <el-option v-for="item in query.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDictionaryGroup, getReferencedDictionaryList } from '@/api/dictionary'
import { getList, doDelete, doEdit, getOrganAuthoritiesPagination } from '@/api/Authority/'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const typeMap = {
        '1': '超级管理员',
        '2': '管理员',
        '3': '普通用户'
      }
      const typeDesc = typeMap[status]
      return typeDesc
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      dialogSubEditFormVisible: false,
      addForVisible: false,
      form: {
        createBy: '',
        createDate: '',
        name: '',
        operationType: '',
        platformType: '',
        parentId: '',
        organId: '',
        organPath: '',
        icon: '',
        path: '',
        code: '',
        remark: '',
        type: '',
        updateBy: '',
        updateDate: '',
        url: '',
        id: ''
      },
      data: [],
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增权限',
        edit: '编辑权限',
        subEdit: '编辑下级权限'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          name: '', // 角色名称
          organId:'',
          tenantId: '',
          organPath: ''
        },
        timeValue: '',
        typeOptions: [{
          value: '1',
          label: '目录'
        }, {
          value: '2',
          label: '功能'
        }],
        platformTypeOptions: [],
        operationTypeOptions: [{
          value: '1',
          label: '查询'
        }, {
          value: '2',
          label: '增加'
        }, {
          value: '3',
          label: '修改'
        }, {
          value: '4',
          label: '删除'
        }],
        value: ''
      }
    }
  },
  created() {
    this.handleAuthorityPlatTypeOptions()
    this.fetchData()
  },
  methods: {
    typeFormat(row, column) {
      //0 1目录，2功能
      if (row.type === 1) {
        return '目录'
      } else if (row.type === 2) {
        return '功能'
      }
    },
    operationTypeFormat(row, column) {
      //0 1查,2增,3改,4删
      if (row.operationType === 1) {
        return '查询'
      } else if (row.operationType === 2) {
        return '新增'
      } else if (row.operationType === 3) {
        return '修改'
      } else if (row.operationType === 4) {
        return '删除'
      }
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getOrganAuthoritiesPagination(this.query.params,
        this.currentPage,
        this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = handleBuildTreeDataStruct(data.entities, 'id', 'parentId')
        this.listLoading = false
      })
    },
    handleAuthorityPlatTypeOptions() {
      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "AusthorityPlatformType" && item.parentId != '0';
      })
      let platformTypeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        platformTypeOptions.push(option)
      }
      this.query.platformTypeOptions = platformTypeOptions

    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.createBy = getCurrentLoginUserId()
      this.form.createDate = ''
      this.form.id = ''
      this.form.operationType = ''
      this.form.parentId = ''
      this.form.icon = ''
      this.form.path = ''
      this.form.code = ''
      this.form.organId = getOrganId()
      this.form.organPath = getOrganPath()
      this.form.remark = ''
      this.form.type = ''
      this.form.updateBy = getCurrentLoginUserId()
      this.form.updateDate = ''
      this.form.url = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(row)
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.id = row.id
      this.form.name = row.name
      this.form.operationType = '' + row.operationType
      this.form.parentId = row.parentId
      this.form.remark = row.remark
      this.form.type = '' + row.type
      this.form.icon = row.icon
      this.form.organId = getOrganId()
      this.form.organPath = getOrganPath()
      this.form.path = row.path
      this.form.code = row.code
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate
      this.form.url = row.url

      this.addForVisible = true

      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSubEditDelete(index, row) {

      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.createBy = ''
      this.form.createDate = ''
      this.form.id = ''
      this.form.operationType = ''
      this.form.parentId = row.id
      this.form.icon = ''
      this.form.path = ''
      this.form.code = ''
      this.form.organId = getOrganId()
      this.form.organPath = getOrganPath()
      this.form.remark = ''
      this.form.type = '2'
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.form.url = ''
      this.addForVisible = false

    },
    handleEditSave() {
      this.form.createBy = getCurrentLoginUserId()
      this.form.updateBy = getCurrentLoginUserId()
      doEdit(this.form).then(response => {
        const data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAssignOrgan(index, row) {
      console.log(row)
    },
    handleAssignRole(index, row) {
      console.log(row)
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
  }
}

</script>
